<?php

class Default_AuthController extends Zend_Controller_Action
{

    private $_mapper = null;

    public function init()
    {
        /* Initialize action controller here */
    	$this->_mapper = new Usuarios_Model_UsuarioMapper();
    	$this->view->messages = $this->_helper->flashMessenger->getMessages();
    }

    public function indexAction()
    {
        // action body
    	$this->_helper->redirector("login","Auth","default");
    }

    public function loginAction()
    {
        // action body
    	$form = new Default_Form_Login();
    	
    	if ($this->getRequest()->isPost()) {
    		$data = $this->getRequest()->getPost();
    		if ($form->isValid($data)) {
    			$dbAdapter = Zend_Db_Table::getDefaultAdapter();
    			$adapter = new Zend_Auth_Adapter_DbTable($dbAdapter, "usuarios",
    					"usuario", "senha", 'SHA1(?)');
    			$adapter->setIdentity($form->getValue('usuario'));
                $adapter->setCredential($form->getValue('senha'));
                
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($adapter);
                if ($result->isValid()) {
                	$info = $adapter->getResultRowObject(null, 'senha');
                	$storage = $auth->getStorage();
                	$storage->write($info);
                	return $this->_helper->redirector("index","index","default");
                } else {
                	$this->_helper->flashMessenger->addMessage('Usuário ou senha inválido!');
                	$this->_helper->redirector("login","Auth","default");
                }
                
    		}else{
    			$form->populate($data);
    		}
    	}
    	if(Zend_Auth::getInstance()->hasIdentity()){
    		$this->_helper->flashMessenger->addMessage('Sem permissão para acessar esta area');
            $this->_helper->redirector("index","index","default");
    	}else{
    		$this->view->form = $form;
    	}
    }

    public function logoutAction()
    {
        // action body
    	$auth = Zend_Auth::getInstance();
    	$auth->clearIdentity();
    	$this->_helper->redirector("login","Auth","default");
    }


}





